import React, { Component, Fragment, useState } from 'react';
import { Form } from '@ant-design/compatible';
import { List, Button, Input, Select, Upload, message, Icon, Avatar } from 'antd';
import { connect, useStore } from 'dva';
import { updateUserInfo } from "../service";

const FormItem = Form.Item;

const MAX_IMG_SIZE = { size: 2 * 1024 * 1024, format: "2M" };

const SecurityView = props => {

  const {
    form: { getFieldDecorator }, dispatch = () => { },
  } = props;
  const [checkValid, setCheckValid] = useState('');

  const handlerSubmit = event => {
    event.preventDefault();
    const { form, currentUser } = props;
    form.validateFields(async err => {
      if (!err) {
        // 判断两次密码输入是否一致
        const input_params = form.getFieldsValue();
        if (input_params['password'] != input_params['password_check']) {
          setCheckValid('error');
          return;
        }
        let hide = message.loading("更新中，请稍候。")
        const response = await updateUserInfo({ password: input_params['password']}, currentUser.userid);
        hide();
        if (response.ok) {
          message.success('更新成功！');
          return;
        }
        message.error(`更新失败！code：${response.status}`)
      }
    });
  };

  return (
      <>
      <div>
        <Form layout="vertical" hideRequiredMark>
          <FormItem label="原密码">
            <Input value={'xxxxxxxxx'} disabled/>
          </FormItem>
          <FormItem 
            label="新密码"
          >
            {getFieldDecorator('password', {
              rules: [
                {
                  required: true,
                  message: '',
                  pattern: /^[a-zA-Z0-9@!]+$/,  // 正则表达式
                  max: 20,
                  min: 8,
                  message: '请输入由字母、数字、@、!组成的8-20位密码！',
                },
              ],
            })(<Input.Password placeholder="请输入新密码!" />)}
          </FormItem>
          <FormItem 
            label="请确认"
            validateStatus={checkValid}
            help={checkValid ? '输入密码不一致！' : null}
          >
            {getFieldDecorator('password_check', {
              rules: [
                {
                  required: true,
                },
              ],
            })(<Input.Password placeholder="请确认密码!"/>)}
          </FormItem>
          <Button type="primary" onClick={ handlerSubmit }>
            确认修改
            </Button>
        </Form>
      </div>
      </>
    );
}

export default connect(({ accountSettings, user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(SecurityView));
